package cn.demoxy.utils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * @auther demo
 * @date 2022/6/13 21:39
 */
public class JWTUtils {

    // 过期时间30分钟
    private static final long EXPIRE_TIME = 5*60*1000;

    private static String TOKEN = "token!Q@W3e4r";


    /**
     * 校验token是否正确
     * @param token 密钥
     * @return 是否正确
     */
    public static boolean verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,30min后过期
     * @return 加密的token
     */
    public static String sign(String username,Long times) {
        Map<String, Object> map = new HashMap();
        map.put("Algorithm","HMAC256");
        map.put("type","JWT");
        String token = null;
      token  = JWT.create()
                .withHeader(map)
                .withClaim("username", username)//私有声明
                .withClaim("current",times)//当前时间截点
                .withExpiresAt(new Date(System.currentTimeMillis()+EXPIRE_TIME))//过期时间
                .withIssuedAt(new Date())//签发时间
                .sign(Algorithm.HMAC256(TOKEN));


        return token;
    }

    /**
     * 获取过期时间
     */
    public static Long getExpire(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("current").asLong();
        }catch (Exception e){
            return null;
        }
    }

}
